<template>
  <el-button type="primary" :size="size" icon="el-icon-download" :disabled="exportLoading" :loading="exportLoading"
    @click="exportClick">{{ exportLoading ? "正在导出" : exportText }}</el-button>
</template>
<script>
  import axios from "axios";
  import {
    getToken
  } from "@/utils/auth";

  export default {
    props: {
      title: String, // Excel名称
      action: {
        type: String,
        default: "/asset/integral/v1/userDetail/export",
      },
      exportText: {
        type: String,
        default: "导出",
      },
      params: {
        type: Object,
        default: {},
      },
      size: {
        type: String,
        default: "",
      },
      type: {
        type: String,
        default: "1",
      }
    },
    data() {
      return {
        exportLoading: false,
      };
    },
    methods: {
      exportClick() {
        if (this.type == '1') {
          this.exportLoading = true;

          const API = process.env.VUE_APP_BASE_API + this.action;
          axios
            .get(API, {
              params: this.params,
              responseType: "arraybuffer",
              headers: {
                // 'Content-Type':	'application/octet-stream;charset=UTF-8',
                "X-Access-Token": getToken(),
              },
            })
            .then((res) => {
              this.handleData(res);
            })
            .finally(() => {
              this.exportLoading = false;
            });
        } else {
          this.exportLoading = true;
          const API = process.env.VUE_APP_BASE_API + this.action;
          axios.post(API, this.params, {
            headers: {
              "X-Access-Token": getToken(),
            },
            responseType: "blob",
          }).then(res => {
            this.handleData(res);
            this.exportLoading = false;
          }).catch(error => {
            this.exportLoading = false;
          })
          // axios
          //   .post(API, {
          //     params: this.params,
          //     responseType: "arraybuffer",
          //     headers: {
          //       "X-Access-Token": getToken(),
          //     },
          //   })
          //   .then((res) => {
          //     this.handleData(res);
          //   })
          //   .finally(() => {
          //     this.exportLoading = false;
          //   });
        }

      },

      handleData(res) {
        const blob = new Blob([res.data]);
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = this.title + ".xls"; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      },
    },
  };

</script>
<style lang="scss" scoped>
</style>
